package net.yunzhanyi.client.controller;

import com.github.pagehelper.PageInfo;
import net.yunzhanyi.client.domain.dto.PoetryDto;
import net.yunzhanyi.client.domain.vo.PageVo;
import net.yunzhanyi.client.service.HotWordsService;
import net.yunzhanyi.client.service.PoetryService;
import net.yunzhanyi.common.core.utils.StringUtils;
import net.yunzhanyi.generic.domain.model.Author;
import net.yunzhanyi.generic.domain.model.Poetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @author bestct
 * @date 2022/9/28
 * @type 类
 */
@Controller
public class SearchController {


    @Autowired
    private PoetryService poetryService;
    @Autowired
    private HotWordsService hotWordsService;

    @GetMapping("/search")
    public String search(
            @RequestParam(value = "keyword", defaultValue = "") String keyword,
            @RequestParam(value = "searchType", defaultValue = "poetry") String searchType,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            Model model) {
        if ("poetry".equals(searchType)) {
            PageInfo<Poetry> poetryInfo = poetryService.searchPoetry(keyword, pageNum, pageSize);
            PageVo<PoetryDto> poetryPageVo = poetryService.copyPageInfo(poetryInfo);
            if (StringUtils.isNotEmpty(keyword) && poetryPageVo.getList() != null && poetryPageVo.getList().size() != 0) {
                hotWordsService.addHotWord(keyword, 2);
            }
            model.addAttribute("dataInfo", poetryPageVo);
        } else if ("author".equals(searchType)) {
            PageInfo<Author> authorInfo = poetryService.searchAuthor(keyword, pageNum, pageSize);
            if (StringUtils.isNotEmpty(keyword) && authorInfo.getList() != null && authorInfo.getList().size() != 0) {
                hotWordsService.addHotWord(keyword, 2);
            }
            model.addAttribute("dataInfo", authorInfo);
        } else {
            return "redirect:/search?keyword=" + keyword + "&pageNum=" + pageNum + "&pageSize=" + pageSize;
        }
        model.addAttribute("keyword", keyword);
        model.addAttribute("searchType", searchType);
        model.addAttribute("pageNum", pageNum);
        model.addAttribute("pageSize", pageSize);
        return "search";
    }

}
